﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using DataContracts;
using System.ServiceModel;

namespace Presention
{
    public partial class CreateNewUser : System.Web.UI.Page
    {
        protected void Page_Load(object sender, EventArgs e)
        {
            if (!IsPostBack)
            {
                Bind();
            }
        }
        private void Bind()
        {

            using (ServiceAgent UserServiceAgent = new ServiceAgent())
            {


                CreateDepartmentDropDownList.DataSource = UserServiceAgent.ServiceClient.GetAllDepartment();
                CreateDepartmentDropDownList.DataTextField = "DepartmentName";
                CreateDepartmentDropDownList.DataValueField = "DepartmentId";
                CreateDepartmentDropDownList.DataBind();
                CreateDepartmentDropDownList.Items.Insert(0, new ListItem("Please Select", "0"));

                CreateRoleDropDownList.DataSource = UserServiceAgent.ServiceClient.GetAllUserRole();
                CreateRoleDropDownList.DataTextField = "RoleName";
                CreateRoleDropDownList.DataValueField = "RoleId";
                CreateRoleDropDownList.DataBind();
                CreateRoleDropDownList.Items.Insert(0, new ListItem("Please Select", "0"));
            }
        }

        /// <summary>
        /// Implement Add New User
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        protected void CreateAddButton_Click(object sender, EventArgs e)
        {
            UserDTO User = new UserDTO();
            User.FirstName = CreateFirstNameTextBox.Text;
            User.LastName = CreateLastNameTextBox.Text;
            User.Department = new DepartmentDTO();
            User.Department.DepartmentId = Convert.ToInt32(CreateDepartmentDropDownList.SelectedValue);
            User.Role = new RoleDTO();
            User.Role.RoleId = int.Parse(CreateRoleDropDownList.SelectedValue);
            using (ServiceAgent UserServiceAgent = new ServiceAgent())
            {
                try
                {
                    UserServiceAgent.ServiceClient.AddNewUser(User);
                    Response.Write("<script>alert('Add successfully');window.location.href='UserList.aspx'</script>");
                }
                catch (FaultException ex)
                {
                    Response.Write("<script>alert('" + ex.Message + "')</script>");
                    Bind();
                }
            }
        }

    }

}

